package com.lql.lqlreader

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.navigation.NavigationView
import com.google.gson.Gson
import com.jaeger.library.StatusBarUtil
import com.lql.lqlreader.androidlearning.ui.AndroidLearningFragment
import com.lql.lqlreader.androidlearning.ui.MyCollectActivity
import com.lql.lqlreader.login.model.User
import com.lql.lqlreader.login.ui.LoginActivity
import com.lql.lqlreader.opensource.OpenSourceActivity
import com.lql.lqlreader.setting.SettingActivity
import com.lql.lqlreader.zhihu.view.ZhiHuDailyFragment
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val INDEX_VIEWPAGER_MOVIE_STR = "电影"
private const val INDEX_VIEWPAGER_ANDROID_STR = "安卓"
private const val INDEX_VIEWPAGER_ZHIHU_STR = "知乎"

/**
 * Class: MainActivity
 * Description: App主界面
 * Date: 2021/06/15
      _____________
     /  / _____ \  \
    /  / /     \ \  \
   /  / /   __  \ \  \
  /  /\ \   \ \ / /\  \
 /  /__\ \___\ V /__\  \_____
/_______\____________\_______|
*/

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    var appBarLayoutVerticalOffset: Int = 0

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setStatusBar() // 初始化状态栏
        initDrawLayout() // 初始化侧滑栏
        initViewPager() // 初始化主体页面

    }

    private fun setStatusBar() {
        StatusBarUtil.setColorForDrawerLayout(this, drawer_layout, resources.getColor(R.color.colorPrimary), StatusBarUtil.DEFAULT_STATUS_BAR_ALPHA)
    }

    private fun initDrawLayout() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false) // 标题栏显示

        // 当发生侧滑时，其他控件会随之动态改变
        val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener {_, verticalOffset ->
            appBarLayoutVerticalOffset = verticalOffset // 计算标题栏垂直偏移量
        })

        // 初始化侧滑界面的菜单选中事件
        navigation.setNavigationItemSelectedListener(this)

        navigation.getHeaderView(0).findViewById<Button>(R.id.btn_login).setOnClickListener {
            startActivity(Intent(this, LoginActivity::class.java))
            drawer_layout.closeDrawer(GravityCompat.START) // GravityCompat.START 参数表示左侧菜单是否打开
        }

        checkLoginUserShow()
    }

    private fun checkLoginUserShow() { // 检查登录情况
        val loginPreference = getSharedPreferences("loginInfo", MODE_PRIVATE)
        val loginUser = loginPreference.getString("loginUser", null)
        val rlUnlogin = navigation.getHeaderView(0).findViewById<RelativeLayout>(R.id.rl_unlogin)
        val rlLogin = navigation.getHeaderView(0).findViewById<RelativeLayout>(R.id.rl_login)

        if (TextUtils.isEmpty(loginUser)) {
            rlUnlogin?.visibility = View.VISIBLE
            rlLogin?.visibility = View.INVISIBLE

            rlUnlogin?.postInvalidate() // 刷新界面
        } else {
            rlLogin?.visibility = View.VISIBLE
            rlUnlogin?.visibility = View.INVISIBLE

            val user = Gson().fromJson(loginUser, User::class.java)
            val tvUsername = rlLogin.findViewById<TextView>(R.id.tv_username)
            tvUsername?.text = user.username // 用户名赋值
        }
    }

    private fun initViewPager() {
        val pages = FragmentPagerItems(this)
        arrayOf(INDEX_VIEWPAGER_ANDROID_STR, INDEX_VIEWPAGER_MOVIE_STR, INDEX_VIEWPAGER_ZHIHU_STR).forEach {
            when (it) {
                INDEX_VIEWPAGER_ANDROID_STR -> pages.add(FragmentPagerItem.of("学Android", AndroidLearningFragment::class.java)) // 第一页要立刻加载
                INDEX_VIEWPAGER_ZHIHU_STR -> {
                    val element by lazy { FragmentPagerItem.of("知乎", ZhiHuDailyFragment::class.java) } // 懒加载
                    pages.add(element)
                }
            }
        }

        mainTabLayout.setCustomTabView { container, position, _ ->
            val icon = LayoutInflater.from(this@MainActivity)
                .inflate(R.layout.index_tab_icon, container, false) as ImageView
            val res = this@MainActivity.resources
            when (position) {
                0 -> icon.setImageDrawable(res.getDrawable(R.mipmap.index_icon_android))
                1 -> icon.setImageDrawable(res.getDrawable(R.mipmap.index_icon_zhihu))
//                2 -> icon.setImageDrawable(res.getDrawable(R.mipmap.index_icon_douban))
                else -> throw IllegalStateException("Invalid position: $position")
            }
            icon
        }
        mainViewPager.offscreenPageLimit = 5
        mainViewPager.adapter = FragmentPagerItemAdapter(supportFragmentManager, pages)
        mainTabLayout.setViewPager(mainViewPager)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_collection -> {
                val loginPreferences = getSharedPreferences("loginInfo", MODE_PRIVATE)
                val loginUser = loginPreferences.getString("loginUser", null)

                if (loginUser == null) {
                    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
                } else {
                    startActivity(Intent(this, MyCollectActivity::class.java))
                    drawer_layout.closeDrawer(GravityCompat.START)
                }
            }

            R.id.nav_open_source -> {
                startActivity(Intent(this, OpenSourceActivity::class.java))
                drawer_layout.closeDrawer(GravityCompat.START)
            }

            R.id.nav_setting -> {
                startActivity(Intent(this, SettingActivity::class.java))
                drawer_layout.closeDrawer(GravityCompat.START)
            }
        }
        return true
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        checkLoginUserShow() // 这里可以直接使用event定义的类的数据
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginoutSuccessEvent) {
        checkLoginUserShow()
    }
}

class LoginoutSuccessEvent {

}

class LoginSuccessEvent {

}
